<!-- 盘点 -->
<template>
  <div id="change">
    <div class="change-top">
      商品：
      <el-input size="small" style="width: 240px;margin-left: 10px;margin-right: 20px;" clearable>
      </el-input>
      日期：
      <el-date-picker size="small" style="width: 140px;" placeholder="选择日期">
      </el-date-picker>
      &nbsp; &nbsp;商品类别：
      <el-select size="small" style="width: 120px;" placeholder="类别"></el-select>
      &nbsp; &nbsp;
   
      <el-button size="small" style="margin-left: 10px;" type="primary">查询</el-button>
      <br>
      <hr>
      <el-button size="small" style="margin-left: 800px;" @click="sendDataToBackend()">保存盘点</el-button>
      <!-- <el-button size="small" type="primary" @click="goto('addChange')">新增盘点</el-button> -->
      <el-button size="small" type="primary">导入</el-button>
      <el-button size="small" type="primary">导出</el-button>
 <el-button size="small" style="margin-left: 10px;" type="primary" @click="generateInventory()">生成盘点</el-button>
    </div>
    <div class="change-content">
     <el-table
      :header-cell-style="{ fontSize: '14px', backgroundColor: '#f4f4f4', color: 'black', textAlign: 'center' }"
      show-summary :summary-method="getSummaries" height="450px" :data="leaves" border
      style="width: 100%; font-size: 13px; color: black;">
      <el-table-column prop="goodcode" label="商品编号" width="150"></el-table-column>
      <el-table-column prop="goodname" label="商品名称" width="150"></el-table-column>
      <el-table-column prop="categoryName" label="商品类别" width="100"></el-table-column>
      <el-table-column prop="brandName" label="品牌" width="100"></el-table-column>
      <el-table-column prop="unitname" label="基本单位" width="120"></el-table-column>
      <!-- 仓库选择列 -->
      <el-table-column label="选择仓库" width="180">
        <template slot-scope="scope">
          <el-select v-model="scope.row.selectedStoreId" placeholder="请选择仓库" @change="handleStoreChange(scope.row)">
            <el-option
              v-for="item in storeList"
              :key="item.shId"
              :label="item.storeHomeName"
              :value="item.shId">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <!-- 动态显示选中仓库的数量 -->
     <el-table-column label="系统数量" width="120">
  <template slot-scope="scope">
    <span v-if="scope.row.selectedStoreId" >
      {{ getStoreQuantity(scope.row, scope.row.selectedStoreId) }}
    </span>
     <input
    style="display:none"
    v-model="scope.row.num"
    type="test"
      aria-hidden="true"/>
  </template>
</el-table-column>
<el-table-column label="盘点数量" width="120">
  <template slot-scope="scope">
    <input
      type="text"
      v-model="scope.row.stockCount"
      @input="handleStockCountChange(scope.row)"
      @blur="handleStockCountChange(scope.row)"
      :style="{ color: scope.row.stockCountStyle }"
       class="stock-input"
    />
  </template>
</el-table-column>
<el-table-column label="盘盈盘亏" width="120">
  <template slot-scope="scope">
    <span v-if="getProfitLoss(scope.row) !== ''" :style="{ color: getProfitLossStyle(scope.row) }">
      {{ getProfitLoss(scope.row) }}
    </span>
    <input
    style="display:none"
    v-model="scope.row.res"
    type="test"
     aria-hidden="true"/>
    
  </template>
</el-table-column>
    </el-table>
       

    </div>
    <el-pagination style="width: 400px;position: relative;left: 700px;bottom: 30px;" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" :current-page="currentPage4" :page-sizes="[100, 200, 300, 400]"
      :page-size="100" layout="total, sizes, prev, pager, next, jumper" :total="400">
    </el-pagination>

  </div>
</template>

<script>
import GoodsChoose from "../public_com/GoodsChoose.vue";

export default {
  name: 'ChangeList',
    components: {
 GoodsChoose
 },
  data() {
    return {//分页参数
     goodsShow: false,
      widStores: [],
      dialogFormVisible: false,
      switchValue: '1',
      value: '',
      input: '',
      value1: '',
      leaves: [],
      storeList: [],
      inventoryRecord:{
        state:0,
        remark:'',
      }
    }
  },
  methods: {
  generateInventory() {
  let surplusItems = [];
  let shortageItems = [];

  this.leaves.forEach(row => {
    const systemQuantity = this.getStoreQuantity(row, row.selectedStoreId);
    const stockCount = Number(row.stockCount);

    if (stockCount > systemQuantity) {
      surplusItems.push(row);
    } else if (stockCount < systemQuantity) {
      shortageItems.push(row);
    }
  });

  if (surplusItems.length > 0 && shortageItems.length === 0) {
    // 只有盈余
    this.$alert('生成盈余盘点的链接', '盈余盘点', {
      confirmButtonText: '确定',
      callback: () => {
        this.generateSurplusLink(surplusItems);
      }
    });
  } else if (shortageItems.length > 0 && surplusItems.length === 0) {
    // 只有短缺
    this.$alert('生成短缺盘点的链接', '短缺盘点', {
      confirmButtonText: '确定',
      callback: () => {
        this.generateShortageLink(shortageItems);
      }
    });
  } else if (surplusItems.length > 0 && shortageItems.length > 0) {
    // 既有盈余又有短缺
    this.$alert('生成盈余和短缺盘点的链接', '综合盘点', {
      confirmButtonText: '确定',
      callback: () => {
        this.generateSurplusLink(surplusItems);
        this.generateShortageLink(shortageItems);
      }
    });
  } else {
    // 没有盈余也没有短缺
    this.$alert('没有盈余或短缺', '盘点结果', {
      confirmButtonText: '确定'
    });
  }
},
generateSurplusLink(items) {
  // 生成盈余链接的逻辑
  console.log('生成盈余链接', items);
  // 可能涉及API调用或生成下载链接
},

generateShortageLink(items) {
  // 生成短缺链接的逻辑
  console.log('生成短缺链接', items);
  // 可能涉及API调用或生成下载链接
},
  sendDataToBackend() {
let extractedData = this.leaves.map(item => {
  return {
    goodcode: item.goodcode,
    num: item.num,
    res: item.res,
    stockCount: item.stockCount,
    selectedStoreId: item.selectedStoreId
  };
});
    var dataForm=new FormData()
    dataForm={
       inventoryRecord: JSON.stringify(this.inventoryRecord),
       inventoryDetailList : JSON.stringify(extractedData)
    }
    this.axios({
      url:'/store/inventory/add',
      method:'post',
      data:dataForm
    
    }).then(rs => {
            console.log(rs.data.status);
            if(rs.data.status==true){
              alert("保存成功");
            }else{
              alert("保存失败")
            }
          })
          .catch(error => {
            console.error('数据发送失败', error);
          });
      
    },
  
  getProfitLoss(row) {
    const systemQuantity = this.getStoreQuantity(row, row.selectedStoreId);
    const stockCount = Number(row.stockCount);
    if (!isNaN(stockCount)&&stockCount!=0) {
      row.res=stockCount - systemQuantity
      return stockCount - systemQuantity;
    } else {
      return '';
    }
  },
  
  getProfitLossStyle(row) {
    const profitLoss = this.getProfitLoss(row);
    return typeof profitLoss === 'number' && profitLoss > 0 ? 'green' : 'red';
  },
    initializeStockCountStyles() {
    this.$data.tableData.forEach(row => {
      const systemQuantity = this.getStoreQuantity(row, row.selectedStoreId);
      const stockCount = Number(row.stockCount);
      if (!isNaN(stockCount)) {
        row.stockCountStyle = stockCount > systemQuantity ? 'green' : 'red';
      } else {
        row.stockCountStyle = 'black';
      }
    });
  },

  handleStockCountChange(row) {
    const systemQuantity = this.getStoreQuantity(row, row.selectedStoreId);
    const stockCount = Number(row.stockCount);
    if (!isNaN(stockCount)) {
      if (stockCount > systemQuantity) {
        this.$set(row, 'stockCountStyle', 'green');
      } else {
        this.$set(row, 'stockCountStyle', 'red');
      }
    } else {
      this.$set(row, 'stockCountStyle', 'black');
    }
  }
,
 getSummaries(param) {
      // 你的汇总方法逻辑
    },
    handleStoreChange(row) {
      // 仓库选择变化时的处理逻辑，可以在这里进行一些操作，比如重新计算数量等
    },
       getStoreQuantity(row, storeId) {
      // 根据行数据和选中的仓库ID获取该仓库的数量
      const storeItem = row.list.find(item => item.wId === storeId);
     row.num = storeItem ? storeItem.store : 0;
      return storeItem ? storeItem.store : 0;
    },
      getWidStore() {
      this.axios.get('/store/leave/getWIdStore')
        .then(rs => {
          this.widStores = rs.data.widStore
        })
    },
     getStoreList() {
      this.axios.get('/info/storeHouse/getAllStore',
        {
          params: {
            cId: 1
          }
        }
      ).then(rs => {
        this.storeList = rs.data.storeList
      })
    },
        getAllStoreLeave() {
      this.axios.get("/store/leave/getStores",
        {
          params: {
            goodcode: this.input
          }
        }
      )
        .then(rs => {
          this.leaves = rs.data.storeList
          console.log(this.leaves)
        })
    }
 
  


  },created(){
        this.getStoreList()
         this.getWidStore()
        this.getAllStoreLeave()
       this.initializeStockCountStyles()
  }

}
</script>

<style scoped>
#change {
  width: 100%;
  height: 100%;
}

.change-top {
  width: calc(100% -20px);
  /* height: 60px; */
  /* background-color: pink; */
  line-height: 60px;
  padding-left: 20px;
  font-size: 13px;
}

.change-content {
  width: 100%;
  height: calc(100% - 60px);
  /* background-color: skyblue; */
}

.el-input,
.el-button {
  font-size: 13px;
}

/* 合计行整体样式修改开始 */
.el-table /deep/ .el-table__footer-wrapper tbody td {
  background-color: #fff1d4;
}

.el-table /deep/ tbody tr:hover>td {
  background-color: #fff1d4 !important;
}

.stock-input {
  border: none;
  outline: none;
  background-color: #f0f0f0;
  padding: 5px;
}

</style>